package com.chat;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.chat.entity.DataPackage;
import com.chat.entity.ServerAction;
import com.chat.entity.User;
import com.chat.entity.event.ChannelEvent;
import com.chat.net.SocketClient;
import com.chat.net.socket.Channel;

import java.io.IOException;

import javax.net.ssl.SSLException;

public class LoginActivity extends AppCompatActivity {

    EditText name,pass;
    ImageView head;
    Button login,regster,setting;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        init();
    }

    public void init(){
        //启动网络服务
        SocketClient.getSocketClient();
        name = findViewById(R.id.login_username);
        pass = findViewById(R.id.login_password);
        head = findViewById(R.id.login_head);
        login = findViewById(R.id.login);
        regster = findViewById(R.id.reg);
        setting = findViewById(R.id.setting);

        //点击事件监听
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strUserName = name.getText().toString().trim();
                String strPassWord = pass.getText().toString().trim();

                //运行login方法
                try {
                    login(strUserName,strPassWord);
                } catch (SSLException e) {
                    e.printStackTrace();
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                }
            }
        });

        regster.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),RegisterActivity.class);
                startActivity(intent);
            }
        });

        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),Setting.class);
                startActivity(intent);
            }
        });
    }

    public void login(final String userName,final String passWord) throws IOException, InterruptedException {

        //handler更新ui
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what == 200){
                    //存储token
                    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("chat",MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("token",(String) msg.obj);
                    editor.commit();
                    editor.apply();
                    SocketClient.getSocketClient().setToken((String) msg.obj);
                    //进入MainActivity
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                    startActivity(intent);
                    finish();
                }
                else{
                    Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                }
            }
        };

        //获取用户信息并赋给User对象
        User user = new User();
        user.setAccount(userName);
        user.setPassword(passWord);
        DataPackage dataPackage = DataPackage.successResponse(user, ServerAction.LOGIN);
        //添加登录请求事件
        SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
            @Override
            public void onChannelEvent(Channel ctx, DataPackage source) {
                //当数据包返回时，把code和token赋给Message
                Message message = Message.obtain();
                message.what = source.getCode();
                message.obj = source.getToken();
                if(source.getDate() instanceof User)
                    message.arg1 = ((User)source.getDate()).getUserId();
                //发送message给handler
                handler.sendMessage(message);
            }
        },dataPackage);
    }
}